package com.kanshu.ksgb.fastread.doudou.module.download.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.DownLoadChapterBean;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.module.download.service.DownloadBookService;

import java.util.List;


public class SimpleTreeAdapter<T> extends TreeListViewAdapter<T> {

	public SimpleTreeAdapter(ListView mTree, Context context, List<DownLoadChapterBean> datas) {
		super(mTree, context, datas);
	}

	private onSelectChapterListener mListener;
	private boolean mIsEdit = true;

	public void setSelectChapterListener(onSelectChapterListener listener){
		this.mListener = listener;
	}

	/**
	 * 设置全选 / 取消全选
	 */
	public void setSelectAllState(boolean isSelect){
		int chapterCount = 0;
		int beansCount = 0;
		for (DownLoadChapterBean parentBean : mNodes) {
            parentBean.is_download = isSelect;
            parentBean.is_canceldownload = isSelect;
			if(!TextUtils.isEmpty(parentBean.id) && isSelect){
				chapterCount += parentBean.chapters.size();
				beansCount += parentBean.group_beans;
			}
            if(!TextUtils.isEmpty(parentBean.id) && parentBean.chapters != null){
                for (DownLoadChapterBean childBean : parentBean.chapters) {
                    childBean.is_download = isSelect;
                }
            }
		}
		if(mListener != null) {
			mListener.selectChapterListener(chapterCount, beansCount);
		}
		notifyDataSetChanged();
	}

	public void setIsEdit(boolean isEdit){
		mIsEdit = isEdit;
	}

	public boolean getIsEdit(){
		return mIsEdit;
	}

	public List<DownLoadChapterBean> getData(){
		return mAllNodes;
	}

	@Override
	public View getConvertView(DownLoadChapterBean bean, int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.item_download_chapter, parent, false);
			viewHolder = new ViewHolder();
			viewHolder.slectState = convertView.findViewById(R.id.select_download_state);
			viewHolder.chapterTitle = convertView.findViewById(R.id.download_chapter_title);
			viewHolder.downloadState = convertView.findViewById(R.id.download_state);
			viewHolder.groupSwitch = convertView.findViewById(R.id.is_show_switch);
			viewHolder.divider = convertView.findViewById(R.id.divider);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.slectState.setOnClickListener(v -> {
            if(mIsEdit && v instanceof ImageView){
                bean.is_download = !bean.is_download;
                ((ImageView) v).setImageResource(bean.is_download ? R.mipmap.ic_dowaload_selected : R.mipmap.ic_dowaload_uncheck);
				notifyData(bean, position);
				statisticalSelect();
            }
        });

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewHolder.divider.getLayoutParams();
		if (!TextUtils.isEmpty(bean.id)) {
			convertView.setBackgroundResource(R.color.white);
			DisplayUtils.visible(viewHolder.groupSwitch);
			viewHolder.groupSwitch.setImageResource(bean.is_show ? R.mipmap.ic_arrow_down : R.mipmap.ic_person_expand);
			initGroupDownloadState(viewHolder, bean);
			params.setMargins(0, 0, 0, 0);
			convertView.setPadding(0, 0, 0, 0);
		}else {
			convertView.setBackgroundResource(R.color.color_fafafa);
			DisplayUtils.gone(viewHolder.groupSwitch);
			initChildDownloadState(viewHolder, bean, position);
			params.setMargins(DisplayUtils.dip2px(convertView.getContext(), 43), 0, 0, 0);
			convertView.setPadding(DisplayUtils.dip2px(convertView.getContext(), 20), 0, 0, 0);
		}
		viewHolder.divider.setLayoutParams(params);
		viewHolder.slectState.setImageResource(bean.is_download ? R.mipmap.ic_dowaload_selected : R.mipmap.ic_dowaload_uncheck);
		viewHolder.chapterTitle.setText(bean.title);
		return convertView;
	}

	private class ViewHolder {
		ImageView slectState;
		TextView chapterTitle;
		TextView downloadState;
		ImageView groupSwitch;
		View divider;
	}

	public interface onSelectChapterListener{
		void selectChapterListener(int chapterCount, int beansCount);
	}

	private void initDownloadState(TextView download_state, int state){
		DisplayUtils.visible(download_state);
		switch (state){
			case DownLoadChapterBean.STATE_WAITING_DOWNLOAD:
				download_state.setTextColor(0xfff4d454);
				download_state.setText("等待下载");
				break;
			case DownLoadChapterBean.STATE_IS_DOWNLOAD:
				download_state.setTextColor(0xfff4d454);
				download_state.setText("下载中");
				break;
			case DownLoadChapterBean.STATE_HAS_DOWNLOAD_ALL:
				download_state.setTextColor(0xffdadada);
				download_state.setText("已下载");
				break;
			case DownLoadChapterBean.STATE_HAS_DOWNLOAD_FAIL:
				download_state.setTextColor(0xffff5a41);
				download_state.setText("下载失败");
				break;
		}
	}

	/**
	 * 初始化组下载状态
	 */
	private void initGroupDownloadState(ViewHolder viewHolder, DownLoadChapterBean bean){
		// 查看本组内容是否全部下载完成
		int noDownLoadCount = 0;
		int failureCount = 0;
		// 统计本组未下载成功章节 and 失败章节数量
		for (DownLoadChapterBean childBean : bean.chapters) {
			if(failureCount == 1){
			    break;
            }
            if(childBean.beans == 0) { // 后台已扣除金豆，检查是否下载失败
                if(MMKVUserManager.getInstance().checkChapterIsFail(childBean.book_id, bean.id, childBean.content_id, childBean.order)){
                    failureCount += 1;
                }
                if(noDownLoadCount != 1 && CacheManager.getInstance().getDownloadChapterFile(childBean.book_id, childBean.order) == null){ // 下载内容为空，需要下载
                    noDownLoadCount += 1;
                }
			} else {    // 后台未扣除金豆，需要下载
                noDownLoadCount += 1;
            }
		}
		DisplayUtils.visible(viewHolder.downloadState);
		// 查看本组内容是否在任务中  --  等待中/下载中

		if(DownloadBookService.isExistQueue(bean.id)){
			// 判断当前队列中下载的分组
			initDownloadState(viewHolder.downloadState, TextUtils.equals(DownloadBookService.getCurrentGroupId(), bean.id) ? DownLoadChapterBean.STATE_IS_DOWNLOAD : DownLoadChapterBean.STATE_WAITING_DOWNLOAD);
		}else if(bean.chapters.size() > 0 && failureCount > 0){
			initDownloadState(viewHolder.downloadState, DownLoadChapterBean.STATE_HAS_DOWNLOAD_FAIL);
		}else if(noDownLoadCount == 0){
			initDownloadState(viewHolder.downloadState, DownLoadChapterBean.STATE_HAS_DOWNLOAD_ALL);
		} else {
			DisplayUtils.gone(viewHolder.downloadState);
		}
	}

	/**
	 * 初始化章节任务下载状态
	 */
	private void initChildDownloadState(ViewHolder viewHolder, DownLoadChapterBean bean, int position){
		// 查看是否下载本章节内容
		if(CacheManager.getInstance().getDownloadChapterFile(bean.book_id, bean.order) != null){
			initDownloadState(viewHolder.downloadState, DownLoadChapterBean.STATE_HAS_DOWNLOAD_ALL);
		} else {
			boolean flag;
			for(int i=position; i < mNodes.size(); i--){
				if(!TextUtils.isEmpty(mNodes.get(i).id)){
					// 查看是否本章节下载失败
					flag = MMKVUserManager.getInstance().checkChapterIsFail(bean.book_id, mNodes.get(i).id, bean.content_id, bean.order);
					if(flag){
						initDownloadState(viewHolder.downloadState, DownLoadChapterBean.STATE_HAS_DOWNLOAD_FAIL);
					}else {
						DisplayUtils.gone(viewHolder.downloadState);
					}
					break;
				}
			}
		}
	}

	/**
	 * 更新书籍
	 */
	private void notifyData(DownLoadChapterBean bean, int position){
		if(!TextUtils.isEmpty(bean.id)){
			bean.is_canceldownload = bean.is_download;
			for(int i=position+1; i < mNodes.size(); i++){
				if(!TextUtils.isEmpty(mNodes.get(i).id)){
					break;
				}else{
					mNodes.get(i).is_download = bean.is_download;
				}
			}
		} else {
			for(int i=position; i < mNodes.size(); i--){
				if(!TextUtils.isEmpty(mNodes.get(i).id)){
					boolean flag = true;
					mNodes.get(i).is_canceldownload = true;
					for(int j=i+1; j < mNodes.size(); j++){
						if(!TextUtils.isEmpty(mNodes.get(j).id)){
							break;
						}else{
							if(!mNodes.get(j).is_download){
								flag = false;
								break;
							}
						}
					}
					mNodes.get(i).is_download = flag;
					break;
				}
			}
		}
		notifyDataSetChanged();
	}

	private void statisticalSelect(){
		int beansCount = 0;
		int chapterCount = 0;
		for (DownLoadChapterBean parentBean : mAllNodes) {
			if(!parentBean.is_canceldownload){
				continue;
			}
			if(parentBean.is_download){
				beansCount += parentBean.group_beans;
				chapterCount += Utils.isEmptyList(parentBean.chapters) ? 0 : parentBean.chapters.size();
				continue;
			}
			for (DownLoadChapterBean childBean : parentBean.chapters) {
				if(childBean.is_download){
					beansCount += childBean.beans;
					chapterCount += 1;
				}
			}

		}
		if(mListener != null) {
			mListener.selectChapterListener(chapterCount, beansCount);
		}
	}
}
